<?php

namespace app\common\model;

use think\Model;
use think\Db;
use think\Loader;
use think\Lang;
use think\Hook;
use Carbon\Carbon;
use think\Request;
use think\Exception;
use app\common\traits\model\TraitModel;
/**
 * 提现
 */
class Cashing extends Model
{
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime         = 'created_at';
    protected $updateTime         = 'updated_at';
    protected $table              = 'withdraw_deposits';
    protected $currency           = [
        'CNY'
    ];
    protected $date_of_withdrawal = [
        ['3-1', '3-31'], 
        ['6-1', '6-30']
    ];

	use TraitModel;

	const APPLY_STATUS    = 0;//申请中
	const PASSED_STATUS   = 1;//申请通过提现中
	const REFUSED_STATUS  = -1;//申请拒绝
	const COMPLETE_STATUS = 2;//提现完成
	const FAILED_STATUS   = -2;//提现失败
    /**
     * 提现申请
     * @param  [type] $amount    [description]
     * @param  [type] $bank_info [description]
     * @param  string $currency  [description]
     * @return [type]            [description]
     */
    public function apply($amount, $bank_info, $currency = 'CNY')
    {
        $is_true = false;
        foreach ($this->date_of_withdrawal as $date_of_withdrawal) {
            if (Carbon::now()->between(Carbon::createFromFormat('m-d', $date_of_withdrawal['0']), Carbon::createFromFormat('m-d', $date_of_withdrawal['1']))) {
                $is_true = true;
                break;
            }
        }

        if (!$amount) {
            throw new Exception(Lang::get("Cash withdrawal amount should be greater than or equal to zero"), 70006); 
        }

        if (!is_numeric($amount)) {
            throw new Exception(Lang::get("Cash amount format error"), 70002);
        }

        $amount = abs($amount);

        if ($amount <= 0) {
            throw new Exception(Lang::get("Cash withdrawal amount should be greater than or equal to zero"), 70003);
        }

        if (!in_array($currency, $this->currency)) {
            throw new Exception(Lang::get("Non monetary unit"), 70004);            
        }

        $this->startTrans();
        try {
            Loader::model('Capitals')->reduceBlance($amount, Request::instance()->user->id, ['remark' => '提现冻结余额']);

            $info = [
                'user_id'   => Request::instance()->user->id, 
                'amount'    => $amount, 
                'status'    => self::APPLY_STATUS, 
                'currency'  => $currency, 
                'bank_num'  => $bank_info['bank_num'],
                'open_bank' => $bank_info['open_bank']
            ];

            $this->create($info, true);

            $this->commit();
            
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
        //后置操作
        Hook::exec('app\\common\\behavior\\Cashing','afterApplyCash', $info);
        return true;
    }

    /**
     * 获取提现银行信息
     * @return [type] [description]
     */
    public function getWithdrawBankInfo()
    {
        return $this->distinct(true)->field('currency,bank_num,open_bank')->where(['user_id' => Request::instance()->user->id, 'status' => self::COMPLETE_STATUS])->column('open_bank', 'bank_num');
    }
	
	/**
	 * 获取提现信息列表
	 * @param $querys
	 */
	public function getCashingList($querys=[]){
		return $this->getInfoList($querys);		
	} 
	 
	 
	/**
	 * 获取提现信息
	 * @param  [type] $id    [description]
	 * @return [type]        [description]
	 */
	public function getCashing($id)
	{
        if ($cashing = $this->get(['id'=>$id])) {
            return $cashing;
        }
        throw new Exception(Lang::get("Withdrawal information does not exist"), 70005);
	}

    /**
     * 通过
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function passed($id)
    {
    	return $this->setStatus(['id' => $id], self::PASSED_STATUS);
    }

    /**
     * 拒绝
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function refused($id)
    {
    	$cashing = $this->getCashing($id);

    	if ($cashing->status == self::REFUSED_STATUS) {
    		return true;
    	}

    	$this->startTrans();
    	try {
            Loader::model('Capitals')->incBlance($cashing->amount, $cashing->user_id, ['remark' => '提现申请拒绝退还']);
    		$this->setStatus(['id' => $id], self::REFUSED_STATUS);
    		$this->commit();
    	} catch (\Exception $e) {
    		$this->rollback();
    		throw $e;
    	}
        //后置操作
        Hook::exec('app\\common\\behavior\\Cashing','afterRefusedCash', $cashing);
        return true;
    }
	
	 /**
     * 失败
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function failed($id)
    {
    	$cashing = $this->getCashing($id);

    	if ($cashing->status == self::FAILED_STATUS) {
    		return true;
    	}

    	$this->startTrans();
    	try {
            Loader::model('Capitals')->incBlance($cashing->amount, $cashing->user_id, ['remark' => '提现失败退还']);
    		$this->setStatus(['id' => $id], self::FAILED_STATUS);
    		$this->commit();
    	} catch (\Exception $e) {
    		$this->rollback();
    		throw $e;
    	}
        //后置操作
        Hook::exec('app\\common\\behavior\\Cashing','afterFailedCash', $cashing);
        return true;
    }
    /**
     * 完成提现
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function complete($id)
    {
        $info = $this->getCashing($id);
        if ($this->setStatus(['id' => $id], self::COMPLETE_STATUS)) {
            //后置操作
            Hook::exec('app\\common\\behavior\\Cashing','afterCompleteCash', $info);
            return true;
        }        
    }

    private function getStatus($id)
    {
    	return $this->getCashing($id, 'status');
    }

    /**
     * 设置提现流水状态
     * @param [type] $where  [description]
     * @param [type] $status [description]
     */
    private function setStatus($where, $status = self::APPLY_STATUS)
    {
    	return $this->update(['status' => $status], $where, true);
    }
}
